#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：back 
@File    ：app_router.py.py
@IDE     ：PyCharm 
@Author  ：七分是你
@Date    ：2024/6/28 下午5:30 
@explain : 
"""
import os
from typing import Annotated

from fastapi import APIRouter, Request, Depends, Header, UploadFile, File
from slowapi import Limiter
from slowapi.util import get_remote_address

from app import dao, utils
from app.service import v1
from app.types import appproto
from app.types.jwtdata import JwtData
from app.utils import StringUtil
from app.utils.aliyun_oss import AliyunOSS
from app.utils.jwt_util import JwtManageUtil

router = APIRouter(prefix="/app", tags=["APP前端相关接口"])

limiter = Limiter(key_func=get_remote_address)


def get_current_user(Authorization: Annotated[str | None, Header()] = None) -> JwtData:
    jwtUtil = JwtManageUtil()
    token = Authorization.replace("Bearer ", "")
    user: JwtData = jwtUtil.decode(token, JwtData)
    return user


@router.post("/upload")
async def upload_file(file: UploadFile = File(...)) -> utils.HttpResponse:
    filename = file.filename
    content = await file.read()
    base_name, suffix = os.path.splitext(filename)
    oss = AliyunOSS()
    key = StringUtil.get_uniqid("hex") + suffix
    result = oss.upload_file(key, content)
    url = ""
    if result:
        url = "https://ln-zhijian.oss-cn-beijing.aliyuncs.com/" + key

    return utils.ResponseSuccess(url)


@router.post("/login/code")
@limiter.limit("5/minute")
async def login_code(data: appproto.MemberCodeLoginRequest, request: Request) -> utils.HttpResponse:
    """
    手机号登录
    """
    result = v1.LoginService.code_login(mobile=data.mobile, code=data.code, utype=data.utype, request=request)
    return result


@router.post("/login/univerify")
@limiter.limit("5/minute")
async def login_univerify(data: appproto.MemberLoginRequest, request: Request) -> utils.HttpResponse:
    result = v1.LoginService.univerify_login(mobile=data.mobile, utype=data.utype, request=request)
    return result


@router.get("/member/info")
async def member_info(UserInfo: JwtData = Depends(get_current_user),
                      request: Request = None) -> utils.HttpResponse:
    member, points = dao.MemberQueryDao.find_member_info(**{'uid': UserInfo.uid})

    user = {"uid": member.uid, "utype": member.utype, "mobile": member.mobile,
            "username": member.username, "email": member.email,
            "last_login_time": StringUtil.format_timestamp_to_str(
                member.last_login_time) if member.last_login_time else '',
            "last_login_address": member.last_login_address,
            "avatar": member.avatar,
            "disable_im": member.disable_im,
            "points": points, "coupon": 0, "order_quantity": 0}
    print("get_current_user===", user)
    return utils.ResponseSuccess(user)
    

@router.post("/member/deregister")
async def member_deregister():
    return {"data": 123}


@router.get("/guestbook/list")
async def guestbook_list(page: int = 1, page_size: int = 10, request: Request = None,
                         UserInfo: JwtData = Depends(get_current_user)) -> utils.HttpResponse:
    result = v1.MemberService.get_guest_book_list(uid=UserInfo.uid, page=page, page_size=page_size, request=request)
    return result


@router.post("/guestbook/add")
async def guestbook_add(data: appproto.GuestBookRequestData,
                        UserInfo: JwtData = Depends(get_current_user)) -> utils.HttpResponse:
    data.uid = UserInfo.uid
    result = v1.MemberService.add(data)
    return result


@router.get("/guestbook/info")
async def get_guestbook_info(request: Request,
                             UserInfo: JwtData = Depends(get_current_user)) -> utils.HttpResponse:
    result = v1.MemberService.get_guestbook_info(uid=UserInfo.uid, request=request)
    return result


@router.post("/complaint/add")
async def guestbook_add(data: appproto.ComplaintData,
                        UserInfo: JwtData = Depends(get_current_user)) -> utils.HttpResponse:
    data.uid = UserInfo.uid
    result = v1.MemberService.add_cmp(data)
    return result


@router.get("/complaint/list")
async def complaint_list(page: int = 1, page_size: int = 10, request: Request = None,
                         UserInfo: JwtData = Depends(get_current_user)) -> utils.HttpResponse:
    result = v1.MemberService.get_complaint_list(uid=UserInfo.uid, page=page, page_size=page_size, request=request)
    return result


@router.get("/article/list")
async def article_list(cid: int = 0, page: int = 1, page_size: int = 10, request: Request = None) -> utils.HttpResponse:
    result = v1.ArticeService.get_artice_list(cid=cid, page=page, page_size=page_size, request=request)
    return result


@router.get("/article/info")
async def article_info(id: int = 0, request: Request = None) -> utils.HttpResponse:
    result = v1.ArticeService.get_article_by_id(id=id, request=request)
    return result


@router.get("/train/list")
async def train_list(key_type: str = '', keyword: str = '', page: int = 1,
                     pagesize: int = 10) -> utils.HttpResponse:
    return v1.TrainService.get_train_list(key_type, keyword, page, pagesize)


@router.get("/train/detail")
async def train_detail(train_id: int, request: Request = None) -> utils.HttpResponse:
    return v1.TrainService.get_train_detail(train_id)
